package com.ship.contract.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ship.common.business.service.impl.BaseServiceImpl;
import com.ship.common.core.utils.StringUtils;
import com.ship.contract.bean.ConFiles;
import com.ship.contract.bean.ConTemplate;
import com.ship.contract.bean.ConTemplateClause;
import com.ship.contract.mapper.ConTemplateMapper;
import com.ship.contract.service.ConFilesService;
import com.ship.contract.service.ConTemplateClauseService;
import com.ship.contract.service.ConTemplateService;
import com.ship.contract.utils.ObjectUtils;
import com.ship.system.api.BpmInstanceService;
import com.ship.system.api.model.ProcessInstanceParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("ConTemplateService")
public class ConTemplateServiceImpl extends BaseServiceImpl<ConTemplateMapper, ConTemplate> implements ConTemplateService {

    @Autowired
    private ConTemplateClauseService conTemplateClauseService;

    @Autowired
    private ConTemplateMapper conTemplateMapper;

    @Autowired
    private ConFilesService conFilesService;

    @Value("${file.http-domain}")
    private String httpUrl;
    @Value("${file.https-domain}")
    private String httpsUrl;

    @Resource
    BpmInstanceService bpmInstanceService;
    @Override
    public void saveCon(ConTemplate conTemplate) {
        Integer type = conTemplate.getTemplateType();
        String contractName = null;
        String contractNumber = null;
        Date signingDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        String date = sdf.format(signingDate);
        String str;
        switch (type) {
            case 1:
                str = "MA-";
                contractName = str+date;
                contractNumber = editContractNumbers(conTemplate,str);
                break;
            case 2:
                str = "TCP-";
                contractName = str+date;
                contractNumber = editContractNumbers(conTemplate,str);
                break;
            case 3:
                str = "CD-";
                contractName = str+date;
                contractNumber = editContractNumbers(conTemplate,str);
                break;
            case 4:
                str = "MSC-";
                contractName = str+date;
                contractNumber = editContractNumbers(conTemplate,str);
                break;
            case 5:
                str = "ISC-CLI-";
                contractName = str+date;
                contractNumber = editContractNumbers(conTemplate,str);
                break;
            case 6:
                str = "RC-";
                contractName = str+date;
                contractNumber = editContractNumbers(conTemplate,str);
                break;
            case 7:
                str = "LC-";
                contractName = str+date;
                contractNumber = editContractNumbers(conTemplate,str);
                break;
            case 8:
                str = "CN-";
                contractName = str+date;
                contractNumber = editContractNumbers(conTemplate,str);
                break;
            case 9:
                str = "ISC-CI-";
                contractName = str+date;
                contractNumber = editContractNumbers(conTemplate,str);
                break;
        }
        conTemplate.setTemplateName(contractName);
        conTemplate.setTemplateNumber(contractNumber);
        super.save(conTemplate);
        //启动审批流程
        ProcessInstanceParam param = new ProcessInstanceParam();
        param.setBussinessId(conTemplate.getId());
        param.setBpmKey(BpmInstanceService.CON_TEMPLATE_BPM_KEY);
        Map<String,Object> map = new HashMap<>();
        try {
            map = ObjectUtils.objectToMap(conTemplate);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        map.put("moduleName","合同范本");
        map.put("reason",conTemplate.getApplyReason());
        param.setParams(map);
        String processInstanceId = bpmInstanceService.startProcessInstance(param);
        conTemplate.setProcessInstanceId(processInstanceId);
        this.updateById(conTemplate);

        ConFiles conFile = new ConFiles();
        conFile.setConId(conTemplate.getId());
        conFile.setFileType(1);
        String path = conTemplate.getPath();
        conFile.setUrl(path);
        conFile.setNewUrl(path);
        conFile.setFileName(path.substring(path.lastIndexOf("/")+1,path.length()));
        //保存附件
        conFilesService.save(conFile);
    }

    @Override
    public Map<String, Object> detail(Long id) {
        Map<String, Object> result = new HashMap<>(5);
        ConTemplate conFiles = super.getById(id);
        String url = conFiles.getPath();
        conFiles.setPath(url.replace(httpUrl, httpsUrl));
        result.put("data", conFiles);
        result.put("templateClause",conTemplateClauseService.listByTemplateId(id));
        result.put("clauseTypes",conTemplateClauseService.clauseTypesByTemplateId(id));
        return result;
    }

    @Override
    public void saveClause(ConTemplateClause conTemplateClause) {
        conTemplateClauseService.save(conTemplateClause);
        //启动审批流程
        ProcessInstanceParam param = new ProcessInstanceParam();
        param.setBussinessId(conTemplateClause.getId());
        param.setBpmKey(BpmInstanceService.SAVE_CLAUSE_BPM_KEY);
        Map<String,Object> map = new HashMap<>();
        try {
            map = ObjectUtils.objectToMap(conTemplateClause);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        map.put("moduleName","合同范本");
        map.put("reason","");
        param.setParams(map);
        String processInstanceId = bpmInstanceService.startProcessInstance(param);
        conTemplateClause.setProcessInstanceId(processInstanceId);
        conTemplateClauseService.updateById(conTemplateClause);
    }

    @Override
    public List<Map<String, Object>> templateClauseTypes(Long id) {
        return conTemplateClauseService.clauseTypesByTemplateId(id);
    }

    @Override
    public String editContractNumbers(ConTemplate conTemplate, String str){
        // 获取所有合同编号
        List<String> strings = conTemplateMapper.getAllContractNumbers();
        // 创建合同编号对象
        String ContractNum;
        int maxNumber = extractAndFindMaxNumber(strings, str);
        ContractNum = str+maxNumber;
        return ContractNum;
    }

    @Override
    public void removeByTemplateId(Long id) {
        conTemplateClauseService.removeByTemplateId(id);
    }

    @Override
    public PageInfo<ConTemplate> queryPage(ConTemplate conTemplate) {
        PageHelper.startPage(conTemplate.getPageNum(),conTemplate.getPageSize());
        String date = DateUtil.format(conTemplate.getArchiveTime(), DatePattern.NORM_DATE_FORMATTER);
        String templateTypeStr = null;
        if (conTemplate.getTemplateType() != null){
            templateTypeStr = String.valueOf(conTemplate.getTemplateType());
        }

        List<ConTemplate> templateList = baseMapper.queryPage(conTemplate.getTemplateName(),templateTypeStr,conTemplate.getTemplateType(),date,conTemplate.getCreateBy());
        PageInfo<ConTemplate> pageInfo = new PageInfo<>(templateList);
        return pageInfo;
    }

    @Override
    public void putClause(ConTemplateClause conTemplateClause) {
        conTemplateClauseService.updateById(conTemplateClause);
    }

    @Override
    public void delClause(Long id) {
        conTemplateClauseService.removeById(id);
    }
}
